import logging
from django.shortcuts import render
from django.views import View
from django import http
from django.core.cache import cache

from . import constants
from areas.models import Area
from meiduo_mall.utils.response_code import RETCODE

logger = logging.getLogger("django")


# 省市区数据
class AreasView(View):
    def get(self, request):
        area_id = request.GET.get("area_id")
        if area_id is None:
            # 读取缓存数据
            province_list = cache.get("province_list")
            if province_list is None:
                try:
                    # 提供省份数据
                    province_model_list = Area.objects.filter(parent__isnull=True)

                    # 序列化省级数据
                    province_list = []
                    for province_model in province_model_list:
                        province_dict = {
                            "id": province_model.id,
                            "name": province_model.name
                        }
                        province_list.append(province_dict)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({"code": RETCODE.DBERR, "errmsg": "省份数据错误"})

                # 存储省份缓存数据
                cache.set("province_list", province_list, constants.AREA_EXPIRATION_TIME)

            return http.JsonResponse({"code": RETCODE.OK, "errmsg": "OK", "province_list": province_list})
        else:
            # 提供市区数据
            try:
                # 读取市区缓存数据
                sub_data = cache.get('sub_area_' + area_id)
                if sub_data is None:
                    province_model = Area.objects.get(id=area_id)
                    sub_model_list = province_model.subs.all()

                    # 序列化城市县区数据
                    sub_list = []
                    for sub_model in sub_model_list:
                        sub_dict = {
                            "id": sub_model.id,
                            "name": sub_model.name,
                        }
                        sub_list.append(sub_dict)
                    sub_data = {
                        "id": province_model.id,
                        "name": province_model.name,
                        "subs": sub_list
                    }
            except Exception as e:
                logger.error(e)
                return http.JsonResponse({"code": RETCODE.DBERR, "errmsg": "城市或县区数据错误"})

            # 存储市区缓存数据
            cache.set('sub_area_' + area_id, sub_data, constants.AREA_EXPIRATION_TIME)

            return http.JsonResponse({"code": RETCODE.OK, "errmsg": "OK", "sub_data": sub_data})
